var crypto = require('crypto');
var fs = require('fs');
var config = require("../config");
var log = require("./logger");
// var Wx_Applets_Config = require('./Wx_Applets_Config');
var requestp = require('request-promise');
const request = require('request');

var WxApi = {
    getsign: function (ret, key) {
        var newkey = Object.keys(ret).sort();
        var sign = "";
        for (var i = 0; i < newkey.length; i++) {
            //向新创建的对象中按照排好的顺序依次增加键值对
            if (newkey[i] != null && newkey[i] != 0 && newkey[i] != "sign" && newkey[i] != "key") {

                sign += newkey[i] + "=" + ret[newkey[i]] + "&";
            }

        }
        sign = sign.substring(0, sign.length - 1);
        sign = sign + "&key=" + key;
        sign = crypto.createHash('md5').update(sign).digest('hex').toUpperCase();

        return sign;
    },
    gettoken: function () {
        console.log("jhajaj");
        return new Promise((resolve, reject) => {
            let APPID = config.wx.appid;
            let secret = config.wx.secret;
            let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${secret}`

            request.get(url, (err, response, data) => {
                console.log("err", err, data);
                if (err) {
                    resolve(false);
                } else {
                    let AccessToken = JSON.parse(data);
                    resolve(AccessToken);
                }
            })
        })


    },
    createwxaqrcode: function (data, path, accessToken, filename) {

        return new Promise((resolve, reject) => {
            var qrcodeurl = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + accessToken
            let options = {
                method: 'POST',
                uri: qrcodeurl,
                encoding: null,
                body: {
                    "page": path,
                    "width": 280,
                    "is_hyaline": false,
                    "scene": data
                },
                json: true
            }


            log.info(JSON.stringify(options));

            var imgname = 'uploads/' + filename + '.jpg'
            var imgnameback = '' + filename + '.jpg'
            fs.exists(imgname, function (exists) {
                //判断图片是否存在
                if (!exists) {
                    //通过微信接口获取小程序码
                    requestp(options)
                        .then(function (body) {
                            var base64Img = body.toString('base64'); // base64图片编码字符串
                            var dataBuffer = new Buffer(base64Img, 'base64');
                            //保存到本地
                            fs.writeFile(imgname, dataBuffer, function (err) {
                                if (err) {
                                    console.log(err);
                                } else {
                                    console.log("保存成功！");

                                    resolve(imgnameback);
                                }
                            });
                        })
                        .catch(function (err) {
                            console.log(err)
                        });
                }
            })



        });


    },
    sendTemplateMessage: function (param, accessToken, json, page) {
        console.log("进来而来2222", param, accessToken);

        let opts = {
            touser: param.openid,
            template_id: param.template_id,
            data: json,
            page: page
        }
        console.log("opts", opts);

        let data = {
            method: 'POST',
            url: `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${accessToken}`,
            body: JSON.stringify(opts),
            header: {
                'content-type': 'application/json' // 默认值
            }
        }
        request(data, function (error, response, data) {
            console.log(error, data);

        });

    }


}

module.exports = WxApi;